package email

import (
	"fmt"

	"gopkg.in/gomail.v2"
)

type Client struct {
	user string
	d    *gomail.Dialer
}

// NewClient returns a new email client instance
// 	host: SMTP host, example: smtp.163.com
// 	port:SMTP port,example: 465
func NewClient(host, user, pwd string, port int) Client {
	return Client{user: user, d: gomail.NewDialer(host, port, user, pwd)}
}

// Send sends the target email info to all mailTo list.
// If fromAlias is not empty,the email from fromat will be like: fromAlias <user@email.com>
func (c Client) SendHtml(subject, bodyHtml, fromAlias string, mailTo ...string) error {
	m := gomail.NewMessage()
	if len(fromAlias) > 0 {
		m.SetHeader("From", fmt.Sprintf("%s<%s>", fromAlias, c.user))
	} else {
		m.SetHeader("From", c.user)
	}
	m.SetHeader("To", mailTo...)
	//m.SetAddressHeader("Cc", "dan@example.com", "Dan")
	m.SetHeader("Subject", subject)
	m.SetBody("text/html", bodyHtml)
	//m.Attach("/home/Alex/lolcat.jpg")

	return c.d.DialAndSend(m)
}
